package com.linwen.excise.base;

import org.junit.Test;

/**
 * @author : linwen
 * @date : 上午11:50 2021/2/28
 */
public class 子串在主串中出现的次数 {

    public static void main(String[] args) {
        String ml = "abcdefaabfgrabdedbaafgjbaab";
        String sl = "ab";
        int count = getSubstringCount(ml, sl);
        System.out.println(count);
        int count1 = getSubstringCount1(ml,sl);
        System.out.println(count1);
    }

    public static int getSubstringCount(String mainString,String subString){
        int ml = mainString.length();
        int sl = subString.length();
        int count = 0;
        if(ml>sl){
            while (true){
                int length = mainString.indexOf(subString);
                if(length>=0){
                    count++;
                    mainString = mainString.substring(length+sl);
                }else{
                    break;
                }
            }
            return count;
        }else{
            return 0;
        }
    }

    public static int getSubstringCount1(String mainString,String subString){
        int count = 0;
        while (mainString.length()>subString.length()){
            int index = mainString.indexOf(subString);
            if(index>=0){
                count++;
                mainString = mainString.substring(index+subString.length());
            }
        }
        return count;
    }
}

